package com.biubiu.firefly.wallpaper.box

import android.annotation.SuppressLint
import android.graphics.Bitmap
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.RecyclerView.ViewHolder
import com.biubiu.firefly.R

@SuppressLint("NotifyDataSetChanged")
class PictureAdapter(
    private val dataList: ArrayList<Bitmap> = arrayListOf()
): RecyclerView.Adapter<PictureAdapter.RecyclerViewHolder>() {
    var onItemClickListener: OnItemClickListener? = null

    fun setData(list: List<Bitmap>){
        dataList.clear()
        dataList.addAll(list)
        notifyDataSetChanged()
    }

    fun updateData(index: Int, bitmap: Bitmap){
        dataList[index] = bitmap
    }

    fun getData(): ArrayList<Bitmap>{
        return dataList
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerViewHolder {
        val view: View =
            LayoutInflater.from(parent.context).inflate(R.layout.item_picture, parent, false)
        return RecyclerViewHolder(view)
    }

    override fun getItemCount(): Int {
        return dataList.size
    }

    override fun onBindViewHolder(holder: RecyclerViewHolder, position: Int) {
        holder.imageView.setImageBitmap(dataList[position])
        holder.rootView.setOnClickListener {
            onItemClickListener?.onItemClick(position)
        }
    }

    inner class RecyclerViewHolder(itemView: View) : ViewHolder(itemView) {
        var rootView = itemView.findViewById<View>(R.id.root_view)!!
        var imageView = itemView.findViewById<ImageView>(R.id.image)!!
    }

    interface OnItemClickListener{
        fun onItemClick(position: Int)
    }
}